import http from '@/utils/http';
import {
  resetRouter
} from '@/router'
// initial state
let state = {
  user: {},
  form: {
    cookie: false,
    username: "",
    password: "",
  },
  token: '',
  roles: false
}

const user = window.localStorage.getItem('user')
if (user) {
  state = JSON.parse(user)
}

/**
 * Getters
 * @type {import('vuex/types').GetterTree<typeof state>}
 */
const getters = {
  getState: state => {
    return state
  },
  getUser: state => {
    return state.user
  },
  getForm: state => {
    return state.form
  },
  getToken: state => {
    return state.token
  },
}
/**
 * Mutations
 *  @type {import('vuex/types').MutationTree<typeof state>}
 */
const mutations = {
  setUser(state, obj) {
    state.user = {
      ...obj
    }
  },
  setForm(state, obj) {
    state.form = {
      ...obj
    }
  },
  setToken(state, obj) {
    state.token = obj
  },
  setRoles(state, roles) {
    state.roles = roles
  }
}
/**
 * Actions
 *  @type {import('vuex/types').ActionTree<typeof state>}
 */
const actions = {
  getInfo({
    commit,
    state
  }) {
    return new Promise(async (resolve, reject) => {
      try {
        const {
          user
        } = await http.get('/sys/user/info')
        commit('setUser', user)
        commit('setRoles', true)
        resolve(user)
      } catch (error) {
        reject(error)
      }
    })
  },
  logOut({
    commit
  }, obj) {
    resetRouter()
    commit('setUser')
    commit('setToken')
    commit('setRoles', false)
  },
}

export default {
  namespaced: true, // 为模块开启命名空间
  state,
  getters,
  mutations,
  actions
}
